import { Button, Form, Input, Select, Radio, Upload, UploadProps, UploadFile, Modal } from "antd";
import { addAccount } from "../../api/accountApi.ts";
import { IDoctor, IOption } from "./public.ts";
import publicStyle from "./public.module.css";
import {
  accountRules, departmentRules, getBase64,
  idcardRules,
  nameRules,
  passwordRules,
  phoneRules,
  purviewRules,
  SELECT_WIDTH,
  sexRules,
  temporaryRules
} from "../../utils/publicStyleAndRules.ts";
import { getAllDepartment } from "../../api/publicApi.ts";
import React, { useEffect, useState } from "react";
import { RcFile } from "antd/es/upload";
import { PlusOutlined } from "@ant-design/icons";
import style from "./addAccount.module.css";
// import   "../../assets/css/AllAccount/addAccount.module.css";


const options: IOption[] = [
  { label: '医务管理员', value: '医务管理员' },
  { label: '医生', value: '医生' },
  { label: '护士', value: '护士' },
  { label: '实习助理', value: '实习助理' },
  { label: '药房', value: '药房' }
]


const formItemLayout = {
  labelCol: { span: 1 },
  wrapperCol: { span: 14 },
};
export default function AddAccount() {

  // 表单
  const [dataForm] = Form.useForm();

  //  下拉列表
  const [departOptions, setOptions] = useState<IOption[]>([]);

  // 添加账号
  const handelAddAccount = async (data: object) => {
    const res = await addAccount(data)
    if (res) {
      dataForm.setFieldsValue({})
    }
  }

  // 获取所有科室数据
  const handelGetAllDepartment = async () => {
    const res = await getAllDepartment();
    if (res) {
      const data = res.data.map((item: IDoctor) => {
        return {
          label: item.name,
          value: item.name
        }
      });
      setOptions(data)
    }
  }

  useEffect(() => {
    handelGetAllDepartment()
  }, []);

  // 提交查询表单
  const onFinish = async (values: any) => {
    // values.head = '1673658829669.jpg'
    const head = fileList[0]?.response?.header;
    // console.log(head)
    // console.log(values, '1')
    values = { ...values, head }
    // console.log(values, '2')

    await handelAddAccount(values)
  };

  // ============================================================
  // 预览状态
  const [previewOpen, setPreviewOpen] = useState(false);
  // 预览图像
  const [previewImage, setPreviewImage] = useState('');
  // 文件列表
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  // 处理取消
  const handleCancel = () => setPreviewOpen(false);
  // 处理预览
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };
  // 处理文件上传
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    // console.log(newFileList)
    setFileList(newFileList.slice(-1)); // 只保留最后一个文件
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  // ============================================================

  return (
    <div className={publicStyle.container}>
      <Form
        form={dataForm}
        colon={false}
        requiredMark={false}
        onFinish={onFinish}
        layout={'horizontal'}
        {...formItemLayout}
        initialValues={{
          layout: 'horizontal'
        }}
      >
        <Form.Item label="医务账号" name="account" rules={accountRules}>
          <Input className={publicStyle.input} placeholder="请输入账号名/手机号/邮箱" />
        </Form.Item>
        <Form.Item label="账号权限" name="purview" rules={purviewRules}>
          <Select defaultValue='请选择账号权限' style={{ width: SELECT_WIDTH }} options={options} />
        </Form.Item>
        <Form.Item label="所属科室" name="department" rules={departmentRules}>
          <Select defaultValue='请选择账号科室' style={{ width: SELECT_WIDTH }} options={departOptions} />
        </Form.Item>
        <Form.Item label="医务密码" name="temporary" rules={temporaryRules}>
          <Input.Password className={publicStyle.input} placeholder="请输入密码" />
        </Form.Item>
        <Form.Item label="确认密码" name="password" dependencies={['temporary']} rules={passwordRules}>
          <Input.Password className={publicStyle.input} placeholder="请确认密码" />
        </Form.Item>
        <Form.Item label="医务姓名" name="name" rules={nameRules}>
          <Input className={publicStyle.input} placeholder="请输入该医务人员姓名" />
        </Form.Item>
        <Form.Item label="性别" name="sex" rules={sexRules}>
          <Radio.Group>
            <Radio value={'男'}>男</Radio>
            <Radio value={'女'}>女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="身份证号" name="idcard" rules={idcardRules}>
          <Input className={publicStyle.input} placeholder="请输入该医务人员身份证号" />
        </Form.Item>
        <Form.Item label="手机号" name="phone" rules={phoneRules}>
          <Input className={publicStyle.input} placeholder="请输入手机号" />
        </Form.Item>
        {/*<Form.Item label="上传照片" name="head" rules={headRules}>*/}
        <Form.Item label="上传照片" name="head">
          {/*action="http://hjj.ink:21099/users/uploadheader"*/}
          {/*action={"http://127.0.0.1:21099/users/uploadheader"}*/}
          <Upload
            action="http://hjj.ink:21099/users/uploadheader"
            listType="picture-card"
            fileList={fileList}
            method="POST"
            onPreview={handlePreview}
            onChange={handleChange}
            maxCount={1}
          >
            {fileList.length >= 1 ? null : uploadButton}
          </Upload>
          <Modal open={previewOpen} title={''} footer={null} onCancel={handleCancel}>
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
          </Modal>
        </Form.Item>
        <Form.Item className={style.operation}>
          <Button className={style.confirm} type="primary" htmlType="submit">确认创建</Button>
          <Button className={style.back} type="default">返回上一级</Button>
        </Form.Item>
      </Form>
    </div>
  )
}
